package org.example.redisson.redission;

import org.junit.Test;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Classname RedissionTest
 * @Description TODO
 * @Date 2021/3/25 11:51 上午
 * @Created by xiangjd
 */
public class RedissionTest {

    /**
     * redisson
     */
    int inventory = 11;
    int NUM = 10;

    @Test
    public void testRedisson() throws InterruptedException {
        ThreadPoolExecutor threadPoolExecutor =
                new ThreadPoolExecutor(inventory, inventory, 10L, TimeUnit.SECONDS, new LinkedBlockingDeque<>(10));
        long start = System.currentTimeMillis();
        Config config = new Config();
        config.useSingleServer().setAddress("redis://127.0.0.1:6379");
        final RedissonClient client = Redisson.create(config);
        final RLock lock = client.getLock("lock1");
        CountDownLatch countDownLatch = new CountDownLatch(11);

        for (int i = 0; i <= NUM; i++) {
            threadPoolExecutor.execute(new Runnable() {
                public void run() {
                    System.out.println(Thread.currentThread().getId() + "争抢锁");
                    lock.lock();
                    inventory--;
                    System.out.println(inventory);
                    countDownLatch.countDown();
                    lock.unlock();
                }
            });
        }
        countDownLatch.await();
        long end = System.currentTimeMillis();
        System.out.println("执行线程数:" + NUM + "   总耗时:" + (end - start) + "  库存数为:" + inventory);
    }
}




